import React, { useEffect, useRef, useState } from 'react'
import { NavBar, Button, Form, List, Input, Toast } from 'antd-mobile'

import style from './index.module.scss'
import { useHistory, useLocation } from 'react-router-dom'
import { LoginFormType } from '@/types/data'
import { useDispatch } from 'react-redux'
import { getMobileCode, login } from '@/store/actions/login'
import { InputRef } from 'antd-mobile/es/components/input'

export default function Login() {
  const history = useHistory()
  const dispatch = useDispatch()
  const location = useLocation<{ from: string }>()
  const [form] = Form.useForm()
  const mobileRef = useRef<InputRef>(null)
  const [count, setCount] = useState(0)
  let timer = useRef(-1)

  const onFinish = async (values: LoginFormType) => {
    console.log(values)
    try {
      await dispatch(login(values))
      // 登录成功提示
      Toast.show({
        icon: 'success',
        content: '登录成功',
        duration: 600,
        afterClose: () => {
          // 返回首页
          const pathname = location?.state?.from || '/home'
          history.replace(pathname)
        },
      })
    } catch (e) {
      console.log(e)
    }
  }

  const onGetCode = async () => {
    const mobile = form.getFieldValue('mobile')
    const errors = form.getFieldError('mobile')
    if (!mobile || errors.length > 0) {
      //要么没输手机号，要么有错误信息
      Toast.show('请输入正确手机号')
      //让手机号这个输入框能够获取焦点
      mobileRef.current?.focus()
      return
    }

    //手机号没问题，可以发请求
    await dispatch(getMobileCode(mobile))
    //开始倒计时
    //1.倒计时的秒数
    //2.开个定时器
    setCount(10)
    // console.log(count, 555)

    //小bug，这里默认ts会识别成node中setInterval,而我们要的是window.setInterval
    timer.current = window.setInterval(() => {
      //setCount（count-1）错误写法，拿的是定格的0
      console.log(count, 57)

      setCount((count) => {
        //实时最新的state中的count
        return count - 1
      })
    }, 1000)
  }

  //倒计时为0 清除定时器
  useEffect(() => {
    if (count === 0) {
      clearInterval(timer.current)
    }
  }, [count])

  // 组件销毁的时候，清理定时器
  useEffect(() => {
    return () => {
      clearInterval(timer.current)
    }
  }, [])

  return (
    <div className={style.root}>
      <NavBar onBack={() => history.go(-1)}></NavBar>

      {/* 表单 */}
      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form
          form={form}
          onFinish={onFinish}
          initialValues={{ mobile: '18003736311', code: '246810' }}
        >
          <Form.Item
            className="login-item"
            name="mobile"
            rules={[
              { required: true, message: '手机号不能为空' },
              { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误' },
            ]}
          >
            <Input placeholder="请输入手机号" ref={mobileRef}></Input>
          </Form.Item>
          <List.Item
            className="login-code-extra"
            extra={
              <span className="code-extra" onClick={onGetCode}>
                {count === 0 ? ' 发送验证码' : count + '秒后重新发送'}
              </span>
            }
          >
            <Form.Item
              className="login-item"
              name="code"
              rules={[
                { required: true, message: '验证码不能为空' },
                { pattern: /^\d{6}$/, message: '验证码格式错误' },
              ]}
            >
              <Input placeholder="请输入验证码"></Input>
            </Form.Item>
          </List.Item>
          <Form.Item>
            <Button
              type="submit"
              color="primary"
              block
              className="login-submit"
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
